import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Input,
  Select,
  Modal,
  Form,
  message,
  Popconfirm,
  Tag,
  Tooltip,
  Badge,
  Drawer,
  Descriptions,
  Tabs,
  Typography,
  Row,
  Col,
  Statistic,
  Progress,
  Rate,
  InputNumber,
  Switch,
  DatePicker,
  List,
  Alert,
  Timeline,
  Divider,
  Slider
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  ReloadOutlined,
  FilterOutlined,
  ExportOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  DollarOutlined,
  TrophyOutlined,
  RiseOutlined,
  FallOutlined,
  LineChartOutlined,
  PieChartOutlined,
  BarChartOutlined,
  BellOutlined,
  SafetyOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TableProps } from 'antd';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;
// const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

interface Portfolio {
  id: string;
  userId: string;
  userName: string;
  userEmail: string;
  totalAssets: number;
  availableBalance: number;
  frozenAmount: number;
  totalReturn: number;
  totalReturnRate: number;
  dayReturn: number;
  dayReturnRate: number;
  riskLevel: 1 | 2 | 3 | 4 | 5;
  riskScore: number;
  allocations: AssetAllocation[];
  positions: Position[];
  riskControls: RiskControl[];
  alerts: Alert[];
  status: 'normal' | 'warning' | 'risk' | 'frozen';
  lastRebalanceDate: string;
  createdAt: string;
  updatedAt: string;
}

interface AssetAllocation {
  category: 'stock' | 'bond' | 'cash' | 'alternative' | 'overseas';
  targetRatio: number;
  currentRatio: number;
  amount: number;
  deviation: number;
}

interface Position {
  id: string;
  productId: string;
  productName: string;
  productCode: string;
  category: string;
  shares: number;
  avgCost: number;
  currentPrice: number;
  marketValue: number;
  unrealizedPnL: number;
  unrealizedPnLRate: number;
  weight: number;
  riskContribution: number;
  lastTradeDate: string;
}

interface RiskControl {
  id: string;
  type: 'stop_loss' | 'take_profit' | 'position_limit' | 'concentration_limit' | 'var_limit';
  name: string;
  threshold: number;
  currentValue: number;
  status: 'normal' | 'warning' | 'triggered';
  isActive: boolean;
  description: string;
  createdAt: string;
}

interface Alert {
  id: string;
  type: 'risk' | 'rebalance' | 'performance' | 'compliance';
  level: 'info' | 'warning' | 'error';
  title: string;
  message: string;
  isRead: boolean;
  createdAt: string;
}

interface InvestmentStats {
  totalPortfolios: number;
  totalAssets: number;
  avgReturn: number;
  riskPortfolios: number;
  activeAlerts: number;
}

const InvestmentManagement: React.FC = () => {
  const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [riskFilter, setRiskFilter] = useState<string>('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [stats, setStats] = useState<InvestmentStats>({
    totalPortfolios: 0,
    totalAssets: 0,
    avgReturn: 0,
    riskPortfolios: 0,
    activeAlerts: 0
  });
  
  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'rebalance' | 'risk_control' | 'allocation'>('rebalance');
  const [form] = Form.useForm();
  
  // 投资组合详情抽屉
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedPortfolio, setSelectedPortfolio] = useState<Portfolio | null>(null);
  
  // 风险控制抽屉
  const [riskDrawerVisible, setRiskDrawerVisible] = useState(false);

  // 加载投资组合数据
  useEffect(() => {
    loadPortfolios();
    loadStats();
  }, [pagination.current, pagination.pageSize, searchText, statusFilter, riskFilter]);

  const loadPortfolios = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockPortfolios: Portfolio[] = [
        {
          id: '1',
          userId: 'user001',
          userName: '张三',
          userEmail: 'zhangsan@example.com',
          totalAssets: 1000000,
          availableBalance: 50000,
          frozenAmount: 0,
          totalReturn: 85000,
          totalReturnRate: 9.3,
          dayReturn: 2500,
          dayReturnRate: 0.25,
          riskLevel: 3,
          riskScore: 65,
          allocations: [
            { category: 'stock', targetRatio: 60, currentRatio: 58, amount: 580000, deviation: -2 },
            { category: 'bond', targetRatio: 30, currentRatio: 32, amount: 320000, deviation: 2 },
            { category: 'cash', targetRatio: 10, currentRatio: 10, amount: 100000, deviation: 0 }
          ],
          positions: [
            {
              id: 'pos1',
              productId: 'WM001',
              productName: '稳健增长基金',
              productCode: 'WM001',
              category: '混合型',
              shares: 100000,
              avgCost: 1.200,
              currentPrice: 1.245,
              marketValue: 124500,
              unrealizedPnL: 4500,
              unrealizedPnLRate: 3.75,
              weight: 12.45,
              riskContribution: 8.2,
              lastTradeDate: '2024-01-15'
            }
          ],
          riskControls: [
            {
              id: 'rc1',
              type: 'stop_loss',
              name: '止损控制',
              threshold: -10,
              currentValue: -2.5,
              status: 'normal',
              isActive: true,
              description: '当总亏损超过10%时触发止损',
              createdAt: '2024-01-01'
            },
            {
              id: 'rc2',
              type: 'position_limit',
              name: '单一持仓限制',
              threshold: 20,
              currentValue: 15.5,
              status: 'normal',
              isActive: true,
              description: '单一产品持仓不超过20%',
              createdAt: '2024-01-01'
            }
          ],
          alerts: [
            {
              id: 'alert1',
              type: 'rebalance',
              level: 'warning',
              title: '资产配置偏离',
              message: '股票配置偏离目标2%，建议进行再平衡',
              isRead: false,
              createdAt: '2024-01-15'
            }
          ],
          status: 'normal',
          lastRebalanceDate: '2024-01-01',
          createdAt: '2023-06-01',
          updatedAt: '2024-01-15'
        },
        {
          id: '2',
          userId: 'user002',
          userName: '李四',
          userEmail: 'lisi@example.com',
          totalAssets: 500000,
          availableBalance: 25000,
          frozenAmount: 10000,
          totalReturn: -15000,
          totalReturnRate: -2.9,
          dayReturn: -1200,
          dayReturnRate: -0.24,
          riskLevel: 4,
          riskScore: 78,
          allocations: [
            { category: 'stock', targetRatio: 70, currentRatio: 75, amount: 375000, deviation: 5 },
            { category: 'bond', targetRatio: 20, currentRatio: 15, amount: 75000, deviation: -5 },
            { category: 'cash', targetRatio: 10, currentRatio: 10, amount: 50000, deviation: 0 }
          ],
          positions: [],
          riskControls: [
            {
              id: 'rc3',
              type: 'stop_loss',
              name: '止损控制',
              threshold: -15,
              currentValue: -2.9,
              status: 'normal',
              isActive: true,
              description: '当总亏损超过15%时触发止损',
              createdAt: '2024-01-01'
            }
          ],
          alerts: [
            {
              id: 'alert2',
              type: 'risk',
              level: 'error',
              title: '风险预警',
              message: '投资组合风险评分过高，建议降低风险敞口',
              isRead: false,
              createdAt: '2024-01-14'
            }
          ],
          status: 'warning',
          lastRebalanceDate: '2023-12-01',
          createdAt: '2023-08-01',
          updatedAt: '2024-01-14'
        }
      ];
      
      setPortfolios(mockPortfolios);
      setPagination(prev => ({ ...prev, total: mockPortfolios.length }));
    } catch (error) {
      message.error('加载投资组合数据失败');
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      // 模拟统计数据
      const mockStats: InvestmentStats = {
        totalPortfolios: 1250,
        totalAssets: 15600000000,
        avgReturn: 7.8,
        riskPortfolios: 85,
        activeAlerts: 23
      };
      setStats(mockStats);
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 表格列定义
  const columns: ColumnsType<Portfolio> = [
    {
      title: '投资者信息',
      key: 'userInfo',
      width: 200,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <div style={{ fontWeight: 500, fontSize: 14 }}>{record.userName}</div>
          <div style={{ fontSize: 12, color: '#666' }}>{record.userEmail}</div>
          <div style={{ fontSize: 12, color: '#666' }}>ID: {record.userId}</div>
        </Space>
      )
    },
    {
      title: '资产规模',
      key: 'assets',
      width: 150,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <div style={{ fontWeight: 500, fontSize: 14 }}>
            ¥{(record.totalAssets / 10000).toFixed(1)}万
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            可用: ¥{(record.availableBalance / 10000).toFixed(1)}万
          </div>
          {record.frozenAmount > 0 && (
            <div style={{ fontSize: 12, color: '#ff4d4f' }}>
              冻结: ¥{(record.frozenAmount / 10000).toFixed(1)}万
            </div>
          )}
        </Space>
      ),
      sorter: (a, b) => a.totalAssets - b.totalAssets
    },
    {
      title: '收益情况',
      key: 'returns',
      width: 150,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <div style={{ 
            fontWeight: 500, 
            color: record.totalReturn >= 0 ? '#52c41a' : '#ff4d4f' 
          }}>
            {record.totalReturn >= 0 ? '+' : ''}¥{(record.totalReturn / 10000).toFixed(1)}万
          </div>
          <div style={{ 
            fontSize: 12, 
            color: record.totalReturnRate >= 0 ? '#52c41a' : '#ff4d4f' 
          }}>
            {record.totalReturnRate >= 0 ? '+' : ''}{record.totalReturnRate.toFixed(2)}%
          </div>
          <div style={{ 
            fontSize: 11, 
            color: record.dayReturn >= 0 ? '#52c41a' : '#ff4d4f' 
          }}>
            今日: {record.dayReturn >= 0 ? '+' : ''}¥{record.dayReturn.toFixed(0)}
          </div>
        </Space>
      ),
      sorter: (a, b) => a.totalReturnRate - b.totalReturnRate
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      width: 120,
      render: (level: number, record) => (
        <Space direction="vertical" size={0}>
          <Rate disabled value={level} count={5} style={{ fontSize: 12 }} />
          <div style={{ fontSize: 12 }}>R{level}</div>
          <div style={{ fontSize: 11, color: '#666' }}>
            评分: {record.riskScore}
          </div>
        </Space>
      ),
      sorter: (a, b) => a.riskLevel - b.riskLevel
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record) => {
        const statusConfig = {
          normal: { color: 'green', text: '正常', icon: <CheckCircleOutlined /> },
          warning: { color: 'orange', text: '预警', icon: <WarningOutlined /> },
          risk: { color: 'red', text: '风险', icon: <CloseCircleOutlined /> },
          frozen: { color: 'gray', text: '冻结', icon: <CloseCircleOutlined /> }
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return (
          <Space>
            <Tag color={config.color} icon={config.icon}>
              {config.text}
            </Tag>
            {record.alerts.filter(a => !a.isRead).length > 0 && (
              <Badge count={record.alerts.filter(a => !a.isRead).length} size="small" />
            )}
          </Space>
        );
      },
      filters: [
        { text: '正常', value: 'normal' },
        { text: '预警', value: 'warning' },
        { text: '风险', value: 'risk' },
        { text: '冻结', value: 'frozen' }
      ]
    },
    {
      title: '最后再平衡',
      dataIndex: 'lastRebalanceDate',
      key: 'lastRebalanceDate',
      width: 120,
      render: (date: string) => {
        const daysDiff = dayjs().diff(dayjs(date), 'day');
        return (
          <Space direction="vertical" size={0}>
            <div style={{ fontSize: 12 }}>{date}</div>
            <div style={{ 
              fontSize: 11, 
              color: daysDiff > 90 ? '#ff4d4f' : '#666' 
            }}>
              {daysDiff}天前
            </div>
          </Space>
        );
      },
      sorter: (a, b) => dayjs(a.lastRebalanceDate).unix() - dayjs(b.lastRebalanceDate).unix()
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewPortfolio(record)}
            />
          </Tooltip>
          <Tooltip title="资产配置">
            <Button 
              type="text" 
              icon={<PieChartOutlined />} 
              size="small"
              onClick={() => handleAssetAllocation(record)}
            />
          </Tooltip>
          <Tooltip title="风险控制">
            <Button 
              type="text" 
              icon={<SafetyOutlined />} 
              size="small"
              onClick={() => handleRiskControl(record)}
            />
          </Tooltip>
          <Tooltip title="再平衡">
            <Button 
              type="text" 
              icon={<BarChartOutlined />} 
              size="small"
              onClick={() => handleRebalance(record)}
            />
          </Tooltip>
          {record.status === 'risk' && (
            <Tooltip title="强制平仓">
              <Popconfirm
                title="确定要强制平仓吗？"
                onConfirm={() => handleForceLiquidation(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  type="text" 
                  icon={<ThunderboltOutlined />} 
                  size="small"
                  danger
                />
              </Popconfirm>
            </Tooltip>
          )}
        </Space>
      )
    }
  ];

  // 处理查看投资组合详情
  const handleViewPortfolio = (portfolio: Portfolio) => {
    setSelectedPortfolio(portfolio);
    setDetailDrawerVisible(true);
  };

  // 处理资产配置
  const handleAssetAllocation = (portfolio: Portfolio) => {
    setSelectedPortfolio(portfolio);
    setModalType('allocation');
    setIsModalVisible(true);
  };

  // 处理风险控制
  const handleRiskControl = (portfolio: Portfolio) => {
    setSelectedPortfolio(portfolio);
    setRiskDrawerVisible(true);
  };

  // 处理再平衡
  const handleRebalance = (portfolio: Portfolio) => {
    setSelectedPortfolio(portfolio);
    setModalType('rebalance');
    setIsModalVisible(true);
  };

  // 处理强制平仓
  const handleForceLiquidation = async (portfolioId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      setPortfolios(prev => prev.map(p => 
        p.id === portfolioId ? { ...p, status: 'frozen' as const } : p
      ));
      message.success('强制平仓操作已执行');
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理批量操作
  const handleBatchOperation = (operation: string) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的投资组合');
      return;
    }
    
    Modal.confirm({
      title: `确定要${operation}选中的${selectedRowKeys.length}个投资组合吗？`,
      onOk: async () => {
        try {
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          if (operation === '批量再平衡') {
            setPortfolios(prev => prev.map(p => 
              selectedRowKeys.includes(p.id) 
                ? { ...p, lastRebalanceDate: dayjs().format('YYYY-MM-DD') } 
                : p
            ));
          } else if (operation === '风险检查') {
            // 模拟风险检查
          }
          
          setSelectedRowKeys([]);
          message.success(`${operation}操作完成`);
        } catch (error) {
          message.error(`${operation}操作失败`);
        }
      }
    });
  };

  // 表格选择配置
  const rowSelection: TableProps<Portfolio>['rowSelection'] = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE
    ]
  };

  // 获取资产配置颜色
  const getAllocationColor = (deviation: number) => {
    if (Math.abs(deviation) <= 2) return '#52c41a';
    if (Math.abs(deviation) <= 5) return '#faad14';
    return '#ff4d4f';
  };

  // 获取分类文本
  const getCategoryText = (category: string) => {
    const categoryMap = {
      stock: '股票',
      bond: '债券',
      cash: '现金',
      alternative: '另类',
      overseas: '海外'
    };
    return categoryMap[category as keyof typeof categoryMap] || category;
  };

  return (
    <div>
      {/* 页面标题和统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={5}>
          <Card>
            <Statistic
              title="投资组合总数"
              value={stats.totalPortfolios}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={5}>
          <Card>
            <Statistic
              title="管理资产"
              value={stats.totalAssets}
              precision={1}
              valueStyle={{ color: '#1890ff' }}
              formatter={(value) => `¥${(Number(value) / 100000000).toFixed(1)}亿`}
            />
          </Card>
        </Col>
        <Col span={5}>
          <Card>
            <Statistic
              title="平均收益率"
              value={stats.avgReturn}
              precision={1}
              suffix="%"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={5}>
          <Card>
            <Statistic
              title="风险组合"
              value={stats.riskPortfolios}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="活跃预警"
              value={stats.activeAlerts}
              prefix={<BellOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        {/* 搜索和筛选栏 */}
        <div style={{ marginBottom: 16 }}>
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={8} md={6}>
              <Search
                placeholder="搜索投资者姓名、邮箱"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onSearch={loadPortfolios}
                enterButton={<SearchOutlined />}
              />
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="状态"
                value={statusFilter}
                onChange={setStatusFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="normal">正常</Option>
                <Option value="warning">预警</Option>
                <Option value="risk">风险</Option>
                <Option value="frozen">冻结</Option>
              </Select>
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="风险等级"
                value={riskFilter}
                onChange={setRiskFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="1">R1 - 低风险</Option>
                <Option value="2">R2 - 中低风险</Option>
                <Option value="3">R3 - 中等风险</Option>
                <Option value="4">R4 - 中高风险</Option>
                <Option value="5">R5 - 高风险</Option>
              </Select>
            </Col>
            <Col xs={24} md={9}>
              <Space>
                <Button icon={<ReloadOutlined />} onClick={loadPortfolios}>
                  刷新
                </Button>
                <Button icon={<FilterOutlined />}>
                  高级筛选
                </Button>
                <Button icon={<ExportOutlined />}>
                  导出报告
                </Button>
                <Button icon={<LineChartOutlined />}>
                  风险分析
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 操作栏 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            {selectedRowKeys.length > 0 && (
              <>
                <Button 
                  type="primary"
                  icon={<BarChartOutlined />}
                  onClick={() => handleBatchOperation('批量再平衡')}
                >
                  批量再平衡
                </Button>
                <Button 
                  icon={<SafetyOutlined />}
                  onClick={() => handleBatchOperation('风险检查')}
                >
                  风险检查
                </Button>
              </>
            )}
          </Space>
          <Text type="secondary">
            {selectedRowKeys.length > 0 && `已选择 ${selectedRowKeys.length} 项`}
          </Text>
        </div>

        {/* 投资组合表格 */}
        <Table<Portfolio>
          columns={columns}
          dataSource={portfolios}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
          scroll={{ x: 1400 }}
        />
      </Card>

      {/* 投资组合详情抽屉 */}
      <Drawer
        title="投资组合详情"
        placement="right"
        width={800}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
      >
        {selectedPortfolio && (
          <Tabs 
            defaultActiveKey="overview"
            items={[
              {
                key: 'overview',
                label: '概览',
                children: (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col span={12}>
                        <Card title="基本信息" size="small">
                          <Descriptions column={1} size="small">
                            <Descriptions.Item label="投资者">{selectedPortfolio.userName}</Descriptions.Item>
                            <Descriptions.Item label="邮箱">{selectedPortfolio.userEmail}</Descriptions.Item>
                            <Descriptions.Item label="总资产">
                              ¥{(selectedPortfolio.totalAssets / 10000).toFixed(1)}万
                            </Descriptions.Item>
                            <Descriptions.Item label="可用余额">
                              ¥{(selectedPortfolio.availableBalance / 10000).toFixed(1)}万
                            </Descriptions.Item>
                            <Descriptions.Item label="风险等级">
                              <Rate disabled value={selectedPortfolio.riskLevel} count={5} style={{ fontSize: 12 }} />
                            </Descriptions.Item>
                          </Descriptions>
                        </Card>
                      </Col>
                      <Col span={12}>
                        <Card title="收益情况" size="small">
                          <Descriptions column={1} size="small">
                            <Descriptions.Item label="总收益">
                              <span style={{ color: selectedPortfolio.totalReturn >= 0 ? '#52c41a' : '#ff4d4f' }}>
                                {selectedPortfolio.totalReturn >= 0 ? '+' : ''}¥{(selectedPortfolio.totalReturn / 10000).toFixed(1)}万
                              </span>
                            </Descriptions.Item>
                            <Descriptions.Item label="收益率">
                              <span style={{ color: selectedPortfolio.totalReturnRate >= 0 ? '#52c41a' : '#ff4d4f' }}>
                                {selectedPortfolio.totalReturnRate >= 0 ? '+' : ''}{selectedPortfolio.totalReturnRate.toFixed(2)}%
                              </span>
                            </Descriptions.Item>
                            <Descriptions.Item label="今日收益">
                              <span style={{ color: selectedPortfolio.dayReturn >= 0 ? '#52c41a' : '#ff4d4f' }}>
                                {selectedPortfolio.dayReturn >= 0 ? '+' : ''}¥{selectedPortfolio.dayReturn.toFixed(0)}
                              </span>
                            </Descriptions.Item>
                            <Descriptions.Item label="今日收益率">
                              <span style={{ color: selectedPortfolio.dayReturnRate >= 0 ? '#52c41a' : '#ff4d4f' }}>
                                {selectedPortfolio.dayReturnRate >= 0 ? '+' : ''}{selectedPortfolio.dayReturnRate.toFixed(2)}%
                              </span>
                            </Descriptions.Item>
                          </Descriptions>
                        </Card>
                      </Col>
                    </Row>
                    
                    <Divider>资产配置</Divider>
                    <Row gutter={[16, 16]}>
                      {selectedPortfolio.allocations.map((allocation, index) => (
                        <Col span={8} key={`allocation-summary-${allocation.category}-${index}`}>
                          <Card size="small">
                            <div style={{ textAlign: 'center' }}>
                              <div style={{ fontSize: 16, fontWeight: 500, marginBottom: 8 }}>
                                {getCategoryText(allocation.category)}
                              </div>
                              <Progress 
                                type="circle" 
                                percent={allocation.currentRatio} 
                                size={80}
                                strokeColor={getAllocationColor(allocation.deviation)}
                              />
                              <div style={{ marginTop: 8, fontSize: 12 }}>
                                <div>目标: {allocation.targetRatio}%</div>
                                <div>当前: {allocation.currentRatio}%</div>
                                <div style={{ color: getAllocationColor(allocation.deviation) }}>
                                  偏离: {allocation.deviation > 0 ? '+' : ''}{allocation.deviation}%
                                </div>
                              </div>
                            </div>
                          </Card>
                        </Col>
                      ))}
                    </Row>
                  </>
                )
              },
              {
                key: 'positions',
                label: '持仓明细',
                children: (
                  <Table
                    dataSource={selectedPortfolio.positions}
                    rowKey="id"
                    size="small"
                    pagination={false}
                    columns={[
                      {
                        title: '产品',
                        key: 'product',
                        render: (_, record) => (
                          <div>
                            <div style={{ fontWeight: 500 }}>{record.productName}</div>
                            <div style={{ fontSize: 12, color: '#666' }}>{record.productCode}</div>
                          </div>
                        )
                      },
                      {
                        title: '持仓',
                        dataIndex: 'shares',
                        render: (shares: number) => shares ? shares.toLocaleString() : '0'
                      },
                      {
                        title: '成本价',
                        dataIndex: 'avgCost',
                        render: (price: number) => price ? `¥${price.toFixed(3)}` : '¥0.000'
                      },
                      {
                        title: '现价',
                        dataIndex: 'currentPrice',
                        render: (price: number) => price ? `¥${price.toFixed(3)}` : '¥0.000'
                      },
                      {
                        title: '市值',
                        dataIndex: 'marketValue',
                        render: (value: number) => value ? `¥${(value / 10000).toFixed(1)}万` : '¥0.0万'
                      },
                      {
                        title: '盈亏',
                        key: 'pnl',
                        render: (_, record) => {
                          const pnl = record.unrealizedPnL || 0;
                          const pnlRate = record.unrealizedPnLRate || 0;
                          return (
                            <div style={{ color: pnl >= 0 ? '#52c41a' : '#ff4d4f' }}>
                              <div>{pnl >= 0 ? '+' : ''}¥{pnl.toFixed(0)}</div>
                              <div style={{ fontSize: 12 }}>
                                {pnlRate >= 0 ? '+' : ''}{pnlRate.toFixed(2)}%
                              </div>
                            </div>
                          );
                        }
                      },
                      {
                        title: '权重',
                        dataIndex: 'weight',
                        render: (weight: number) => weight ? `${weight.toFixed(1)}%` : '0.0%'
                      }
                    ]}
                  />
                )
              },
              {
                key: 'alerts',
                label: '预警信息',
                children: (
                  <Timeline>
                    {selectedPortfolio.alerts.map((alert, index) => (
                      <Timeline.Item 
                        key={`alert-${alert.id || index}-${alert.createdAt}`}
                        color={alert.level === 'error' ? 'red' : alert.level === 'warning' ? 'orange' : 'blue'}
                      >
                        <div>
                          <div style={{ fontWeight: 500, marginBottom: 4 }}>
                            {alert.title}
                            {!alert.isRead && <Badge status="processing" style={{ marginLeft: 8 }} />}
                          </div>
                          <div style={{ color: '#666', marginBottom: 4 }}>{alert.message}</div>
                          <div style={{ fontSize: 12, color: '#999' }}>{alert.createdAt}</div>
                        </div>
                      </Timeline.Item>
                    ))}
                  </Timeline>
                )
              }
            ]}
          />
        )}
      </Drawer>

      {/* 风险控制抽屉 */}
      <Drawer
        title="风险控制设置"
        placement="right"
        width={600}
        open={riskDrawerVisible}
        onClose={() => setRiskDrawerVisible(false)}
      >
        {selectedPortfolio && (
          <div>
            <Alert
              message="风险控制状态"
              description={`当前风险评分: ${selectedPortfolio.riskScore}，风险等级: R${selectedPortfolio.riskLevel}`}
              type={selectedPortfolio.status === 'normal' ? 'success' : 'warning'}
              style={{ marginBottom: 16 }}
            />
            
            <List
              dataSource={selectedPortfolio.riskControls}
              renderItem={(item) => (
                <List.Item
                  key={item.id}
                  actions={[
                    <Switch 
                      checked={item.isActive} 
                      onChange={(checked) => {
                        // 处理开关状态变化
                        message.success(`${item.name}已${checked ? '启用' : '禁用'}`);
                      }}
                    />
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <Space>
                        {item.name}
                        <Tag color={item.status === 'normal' ? 'green' : item.status === 'warning' ? 'orange' : 'red'}>
                          {item.status === 'normal' ? '正常' : item.status === 'warning' ? '预警' : '触发'}
                        </Tag>
                      </Space>
                    }
                    description={
                      <div>
                        <div>{item.description}</div>
                        <div style={{ marginTop: 8 }}>
                          <Progress 
                            percent={(Math.abs(item.currentValue) / Math.abs(item.threshold)) * 100}
                            strokeColor={item.status === 'normal' ? '#52c41a' : item.status === 'warning' ? '#faad14' : '#ff4d4f'}
                            format={() => `${item.currentValue}${item.type.includes('rate') ? '%' : ''} / ${item.threshold}${item.type.includes('rate') ? '%' : ''}`}
                          />
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
            
            <Divider />
            
            <Button type="primary" block>
              添加新的风险控制规则
            </Button>
          </div>
        )}
      </Drawer>

      {/* 操作模态框 */}
      <Modal
        title={
          modalType === 'rebalance' ? '投资组合再平衡' :
          modalType === 'allocation' ? '资产配置调整' : '风险控制设置'
        }
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        {modalType === 'rebalance' && selectedPortfolio && (
          <div>
            <Alert
              message="再平衡建议"
              description="系统检测到您的资产配置偏离目标，建议进行再平衡操作。"
              type="info"
              style={{ marginBottom: 16 }}
            />
            
            <div style={{ marginBottom: 16 }}>
              <Title level={5}>当前配置 vs 目标配置</Title>
              {selectedPortfolio.allocations.map((allocation, index) => (
                <div key={index} style={{ marginBottom: 12 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                    <span>{getCategoryText(allocation.category)}</span>
                    <span style={{ color: getAllocationColor(allocation.deviation) }}>
                      {allocation.currentRatio}% (目标: {allocation.targetRatio}%)
                    </span>
                  </div>
                  <Progress 
                    percent={allocation.currentRatio} 
                    strokeColor={getAllocationColor(allocation.deviation)}
                    trailColor="#f0f0f0"
                  />
                </div>
              ))}
            </div>
            
            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button onClick={() => setIsModalVisible(false)}>取消</Button>
                <Button type="primary" onClick={() => {
                  message.success('再平衡操作已提交');
                  setIsModalVisible(false);
                }}>
                  执行再平衡
                </Button>
              </Space>
            </div>
          </div>
        )}
        
        {modalType === 'allocation' && selectedPortfolio && (
          <div>
            <Form layout="vertical">
              <Title level={5}>调整目标配置</Title>
              {selectedPortfolio.allocations.map((allocation, index) => (
                <Form.Item 
                  key={index}
                  label={getCategoryText(allocation.category)}
                  style={{ marginBottom: 16 }}
                >
                  <Row gutter={16} align="middle">
                    <Col span={12}>
                      <Slider 
                        min={0} 
                        max={100} 
                        value={allocation.targetRatio}
                        marks={{ [allocation.targetRatio]: `${allocation.targetRatio}%` }}
                      />
                    </Col>
                    <Col span={6}>
                      <InputNumber 
                        min={0} 
                        max={100} 
                        value={allocation.targetRatio}
                        formatter={value => `${value}%`}
                        parser={value => Number(value!.replace('%', ''))}
                      />
                    </Col>
                    <Col span={6}>
                      <Text type="secondary">
                        当前: {allocation.currentRatio}%
                      </Text>
                    </Col>
                  </Row>
                </Form.Item>
              ))}
              
              <div style={{ textAlign: 'right' }}>
                <Space>
                  <Button onClick={() => setIsModalVisible(false)}>取消</Button>
                  <Button type="primary" onClick={() => {
                    message.success('配置调整已保存');
                    setIsModalVisible(false);
                  }}>
                    保存配置
                  </Button>
                </Space>
              </div>
            </Form>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default InvestmentManagement;